<script setup lang="ts">
import CustomNavBar from './components/CustomNavBar.vue'
import Swiper from '@/components/Swiper.vue'
import Category from './components/Category.vue'
import Hot from './components/Hot.vue'
import Guess from '@/components/Guess.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { getBannerAPI, getCategoryAPI, getHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'

// 轮播图
const bannerList = ref<BannerItem[]>([])
const getBannerData = async () => {
  let res = await getBannerAPI()
  bannerList.value = res.result
}
// 分类
const categoryList = ref<CategoryItem[]>([])
const getCategoryData = async () => {
  let res = await getCategoryAPI()
  categoryList.value = res.result
}
// 热门
const hotList = ref<HotItem[]>([])
const getHotData = async () => {
  let res = await getHotAPI()
  hotList.value = res.result
}
// 获取猜你喜欢组件实例
import { useGuessList } from '@/hooks'
const { guessRef, onScrolltolower } = useGuessList()

// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  // 重新加载数据
  await Promise.all([getBannerData(), getCategoryData(), getHotData(), guessRef.value?.resetData()])
  isTriggered.value = false
}
// 是否加载中标记(骨架屏)
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  // 重新加载数据
  await Promise.all([getBannerData(), getCategoryData(), getHotData()])
  isLoading.value = false
})
</script>

<template>
  <view class="viewport">
    <!-- 自定义导航栏 -->
    <CustomNavBar />
    <scroll-view
      scroll-y
      class="scroll-view"
      @scrolltolower="onScrolltolower"
      refresher-enabled
      :refresher-triggered="isTriggered"
      @refresherrefresh="onRefresherrefresh"
    >
      <PageSkeleton v-if="isLoading" />
      <view v-else>
        <!-- 自定义轮播图 -->
        <Swiper :list="bannerList" />
        <!-- 分类标题 -->
        <Category :list="categoryList" />
        <!-- 热门推荐 -->
        <Hot :list="hotList" />
        <Guess ref="guessRef" />
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
.viewport {
  height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  position: relative;

  .scroll-view {
    flex: 1;
  }
}
</style>
